<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
const props = defineProps({
  countdown: Number
})
const timeLeft = ref(props.countdown)
let intervalId = null

// 格式化时间显示
const formattedTime = computed(() => {
  if (timeLeft.value === -1) return '已截至'
  const minutes = Math.floor(timeLeft.value / 60)
  const seconds = timeLeft.value % 60
  return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`
})

// 倒计时逻辑
const startCountdown = () => {
  intervalId = setInterval(() => {
    if (timeLeft.value > 0) {
      timeLeft.value--
    } else {
      clearInterval(intervalId)
    }
  }, 1000)
}

// 组件挂载时启动倒计时
onMounted(() => {
  startCountdown()
})

// 组件卸载前清除定时器
onBeforeUnmount(() => {
  if (intervalId) {
    clearInterval(intervalId)
  }
})
</script>
<template>
  {{ formattedTime }}
</template>
<style scoped></style>
